<?php

class Admin_LoginController extends Zend_Controller_Action {

    public function init()
    {
        $this->_helper->layout->setLayout('login');

        $this->view->headLink()->appendStylesheet('/css/login.css');
        $this->view->headScript()->appendFile('/js/jquery-1.3.2.min.js');
        $this->view->headScript()->appendFile('/js/easyTooltip.js');
        $this->view->headScript()->appendFile('/js/jquery-ui-1.7.2.custom.min.js'); 
    }

    public function preDispatch() 
    {

        if (admin_Model_Login::isLoggedIn()) {
            $this->view->loggedIn = true;
        }

        $this->view->user = admin_Model_Login::getIdentity();
    }

    public function indexAction() {
        $this->_forward('login');
    }

    public function loginAction() {
        
        $this->view->headTitle('Ingresar al Sistema');

        $form = new admin_Form_Login();
        $form->setAction('/admin/login/');


        if ($this->getRequest()->isPost()) {

            $params = $this->_request->getPost();

            if (!$form->isValid($params)) {

                $form->populate($params);
                $this->view->form = $form;
                return $this->render();
            }


            try {

                $login = new admin_Model_Login();
                $login->setMessage('El correo y la clave no coinciden.', admin_Model_Login::NOT_IDENTITY);
                $login->setMessage('La clave es incorrecta', admin_Model_Login::INVALID_CREDENTIAL);
                $login->setMessage('Los los campos de correo y clave no pueden quedar en blanco.', admin_Model_Login::INVALID_LOGIN);
                $login->login($form->correo->getValue(), $form->clave->getValue());
                $this->_redirect("/admin/");
            
                
            } catch (Exception $e) {

                $responseLogin = $e->getMessage();
            }

            $this->view->responseLogin = $responseLogin;
        }


        $this->view->form = $form;
    }

    public function logoutAction() {
        if (admin_Model_Login::isLoggedIn()) {
            $auth = new admin_Model_Login();
            $auth->logout();
        }

        $this->_redirect('/admin/login/');
    }

}